import { client, getFileNameUUID } from '@/common/ali-oss'

const oss = {
  data() {
    return {
      host: 'yiya-erp.oss-cn-shanghai.aliyuncs.com', //oss地址
      ossData: {},
    }
  },
  methods: {
    returnData(res) {
      if (res.data == undefined) {
        this.$message.error('上传失败,请重试!')
        return
      }
    },
    //上传
    cropperUpload(filePath, data) {
      return new Promise((resolve, reject) => {
        let fileName = filePath + '_' + getFileNameUUID() + '.png'
        client(this.ossData)
          .put(`${filePath}/${fileName}`, data)
          .then((result) => {
            resolve(result)
          })
          .catch((err) => {
            reject('err:', err)
          })
      })
    },
    //头像上传
    async beforeUploads(file) {
      if (file.type.indexOf('image/') == -1) {
        this.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
      } else {
        await this.$store.dispatch('GetOSS').then((res) => {
          this.returnData(res)
          this.ossData = res.data
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => {
            this.options.img = reader.result
          }
        })
      }
    },
    //多张上传   :before-upload="beforeUpload" :http-request="requestUpload" :on-preview="handlePictureCardPreview"  :on-exceed="handleExceed" :on-remove="handleRemove"
    async beforeUpload(file) {
      let fileType = file.type
      if (fileType === 'image/jpeg' || fileType === 'image/png') {
        await this.$store.dispatch('GetOSS').then((res) => {
          this.returnData(res)
          this.ossData = res.data
        })
      } else {
        this.$message.error('请插入图片类型文件(jpg/jpeg/png)')
        return false
      }
    },

    // 富文本图片上传前
    async quillImgBefore(file) {
      let fileType = file.type
      if (fileType === 'image/jpeg' || fileType === 'image/png') {
        await this.$store.dispatch('GetOSS').then((res) => {
          this.returnData(res)
          this.ossData = res.data
        })
      } else {
        this.$message.error('请插入图片类型文件(jpg/jpeg/png)')
        return false
      }
    },
  },
}

export default oss
